package com.sangananitsolution.fragments;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import Utiliypackage.UilityClassFroTime;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.sangananitsolution.gogoproject.R;

public class Mysearch_SearchOption extends Fragment {

	EditText edsubrub1, edsubrub2, edsubrub3, edpost1, edpost2, edpost3,
			editem, edsuburbpost, edsitytown, edstate;
	ImageView sunmitbutton;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.mysearchbylocationanditem,
				container, false);
		edsubrub1 = (EditText) view.findViewById(R.id.etstub1Mysearch1);
		edsubrub2 = (EditText) view.findViewById(R.id.etstubmysearch3);
		edsubrub3 = (EditText) view.findViewById(R.id.etstubmysearch4);
		edpost1 = (EditText) view.findViewById(R.id.etpostMyseacrh1);
		edpost2 = (EditText) view.findViewById(R.id.etpostCodemysearch2);
		edpost3 = (EditText) view.findViewById(R.id.etpostCodemysearch4);
		editem = (EditText) view.findViewById(R.id.edforItem);
		edsuburbpost = (EditText) view.findViewById(R.id.edforPsost);
		edsitytown = (EditText) view.findViewById(R.id.etforcitytown);
		edstate = (EditText) view.findViewById(R.id.edforstate);
		sunmitbutton = (ImageView) view
				.findViewById(R.id.imgsubmitformysearchloction);
		sunmitbutton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				new MysearchLocationAPi().execute();

			}
		});

		view.findViewById(R.id.imgmackarrowMySearch).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// move to previous page

						android.app.FragmentManager fragmentManager = getFragmentManager();
						android.app.FragmentTransaction fragmentTransaction = fragmentManager
								.beginTransaction();

						fragmentTransaction
								.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

						fragmentTransaction.addToBackStack(null);
						fragmentTransaction.replace(R.id.mainfragmentlayout,
								new MySearch());
						fragmentTransaction.commit();

					}
				});
		return view;
	}

	public void onBackPressed() {
		// handle back press event
	}

	private class MysearchLocationAPi extends AsyncTask<String, String, String> {
		ArrayList<String> description = new ArrayList<String>();
		ArrayList<String> suburb = new ArrayList<String>();
		ArrayList<String> startdate = new ArrayList<String>();
		ArrayList<String> startime = new ArrayList<String>();
		ArrayList<String> finishtime = new ArrayList<String>();
		ArrayList<String> productImagesarray = new ArrayList<String>();
		ArrayList<String> productID = new ArrayList<String>();
		ArrayList<String> garageSaleTitle = new ArrayList<String>();
		ArrayList<String> oneOrTwoDaySale = new ArrayList<String>();
		ArrayList<String> unitStreeNo = new ArrayList<String>();
		ArrayList<String> streeName = new ArrayList<String>();
		ArrayList<String> city = new ArrayList<String>();
		ArrayList<String> state = new ArrayList<String>();
		ArrayList<String> postCodearray = new ArrayList<String>();
		ArrayList<String> earlyBirdMessage = new ArrayList<String>();
		ArrayList<String> badWeatherMessage = new ArrayList<String>();
		ArrayList<String> goodsTypearray = new ArrayList<String>();
		ArrayList<String> currentUser = new ArrayList<String>();
		ArrayList<String> longitude = new ArrayList<String>();
		ArrayList<String> latitude = new ArrayList<String>();
		private ProgressDialog pDialog;
		private final String URL = "http://garagesalesagogo.com.au/ProductService.asmx?op=SearchProducts1";
		private final String SOAP_ACTION = "http://tempuri.org/SearchProducts1";
		private String TAG = "PGGURU";

		@Override
		protected String doInBackground(String... params) {
			Log.i(TAG, "I am in doInBackground");
			SoapObject searchProducts = null;
			SoapObject postCode = null;
			SoapObject criteriaobj = null;

			searchProducts = new SoapObject("http://tempuri.org/",
					"SearchProducts");
			criteriaobj = new SoapObject("http://tempuri.org/", "criteria");

			postCode = new SoapObject("http://tempuri.org/", "PostCode");
			postCode.addProperty("string", edpost1.getText().toString());
			// postCode.addProperty("string", edpost2.getText().toString());

			criteriaobj.addSoapObject(postCode);
			searchProducts.addSoapObject(criteriaobj);

			// Create envelope
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			// Set output SOAP object
			envelope.setOutputSoapObject(searchProducts);
			envelope.implicitTypes = true;
			// Create HTTP call object
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

			SoapObject searchProductsResponse = null;
			SoapObject searchProductsResult = null;
			SoapObject productDetails = null;
			
			SoapObject productImagesURL = null;
			
			SoapObject location = null;
			

			try {
				// Invole web service
				androidHttpTransport.call(SOAP_ACTION, envelope);
				// Get the response
				searchProductsResponse = (SoapObject) envelope.bodyIn;
System.out.print(searchProductsResponse);
for (int i = 0; i < searchProductsResponse.getPropertyCount(); i++) {

					searchProductsResult = (SoapObject) searchProductsResponse
							.getProperty(i);
					for (int j = 0; j < searchProductsResult.getPropertyCount(); j++) {
						productDetails = (SoapObject) searchProductsResult
								.getProperty(j);

						String startdatevalue = (productDetails
								.getPropertyAsString("StartDate"));

						String starttimevalue = productDetails
								.getPropertyAsString("SaleStartTime");
						// finding the system date

						
						
						
					//	UilityClassFroTime uilityClassFroTime=new UilityClassFroTime(startdatevalue, starttimevalue);
						String successvalue =	new UilityClassFroTime(startdatevalue, starttimevalue).testForeligbleEntry();
						
					/*	
						String successvalue = testForeligbleEntry(
								startdatevalue, starttimevalue);*/

						try {

							if (Integer.parseInt(successvalue) > -3) {
								
								description.add(productDetails
										.getPropertyAsString("Description"));
								suburb.add(productDetails
										.getPropertyAsString("Suburb"));

								try {
									productImagesURL = (SoapObject) productDetails
											.getProperty("ProductImagesURL");
									productImagesarray.add(productImagesURL
											.getPropertyAsString("string"));
									
								} catch (Exception e) {

									productImagesarray
											.add("~/ProductImages/2015215234459_323.png;");
									
								}

								startdate.add(productDetails
										.getPropertyAsString("StartDate"));
								startime.add(productDetails
										.getPropertyAsString("SaleStartTime"));
								finishtime.add(productDetails
										.getPropertyAsString("SaleFinishTime"));
								productID.add(productDetails
										.getPropertyAsString("ProductId"));
								garageSaleTitle
										.add(productDetails
												.getPropertyAsString("GarageSaleTitle"));
								oneOrTwoDaySale
										.add(productDetails
												.getPropertyAsString("OneOrTwoDaySale"));
								unitStreeNo.add(productDetails
										.getPropertyAsString("UnitStreeNo"));
								streeName.add(productDetails
										.getPropertyAsString("StreeName"));
								city.add(productDetails
										.getPropertyAsString("City"));
								state.add(productDetails
										.getPropertyAsString("State"));
								postCodearray.add(productDetails
										.getPropertyAsString("PostCode"));
								earlyBirdMessage
										.add(productDetails
												.getPropertyAsString("EarlyBirdMessage"));
								badWeatherMessage
										.add(productDetails
												.getPropertyAsString("BadWeatherMessage"));
								goodsTypearray.add(productDetails
										.getPropertyAsString("GoodsType"));

								currentUser.add(productDetails
										.getPropertyAsString("CurrentUser"));

								try {
									location = (SoapObject) productDetails
											.getProperty("Location");

									latitude.add(location
											.getPropertyAsString("Longitude"));
									longitude.add(location
											.getPropertyAsString("Latitude"));
								} catch (Exception e) {
									e.printStackTrace();
								}

							}

						} catch (Exception exception) {

						}
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

	/*	public String testForeligbleEntry(String startdatevalue,
				String starttimevalue) {

			// finding the system current time and date of system
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
			Date date = new Date();
			String currentDate = sdf.format(date).toString();

			// getting minutes and hours from server
			String str = starttimevalue;
			int hours = 0, minutes = 0;
			DateFormat formatters = new SimpleDateFormat("h:mm a");
			Date dates;
			try {
				dates = formatters.parse(str);

				hours = dates.getHours();
				minutes = dates.getMinutes();
			} catch (ParseException e1) {

				e1.printStackTrace();
			}

			String salesStartDate = startdatevalue + " " + hours + ":"
					+ minutes;

			DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

			DateTimeFormatter formatter = DateTimeFormat.forPattern(
					"MM/dd/yyyy HH:mm").withZone(timeZone);

			DateTime dateTimeStart = formatter.parseDateTime(currentDate);
			DateTime dateTimeStop = formatter.parseDateTime(salesStartDate);
			Period period = new Period(dateTimeStart, dateTimeStop);
			PeriodFormatter periodFormatter = PeriodFormat.getDefault();
			String output = periodFormatter.print(period);

			// getremainingsalestime(output,finishtimemain);

			String splitdatetime[] = output.split("and");

			for (int i = 0; i < splitdatetime.length; i++)
				splitdatetime[i] = splitdatetime[i].trim();

			String result = "", tagvalue = "";

			for (int i = 0; i < splitdatetime.length; i++) {
				String datetime = splitdatetime[i];
				String[] timePosNegativesplit = datetime.split(",");
				String timePosNegative = timePosNegativesplit[0];
				String[] diftime = timePosNegative.split(" ");
				String dtime = diftime[0];

				String tag = diftime[1];
				if ((tag.equals("day")) && (Integer.parseInt(dtime) > 0)) {

					result = dtime;
					break;

				}

			}
			return result;

		}*/

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "I am in onPreExecute");
			// Showing progress dialog

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait for match List...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected void onPostExecute(String result) {

			pDialog.dismiss();
			Log.i(TAG, "I am in onPostExecute");
			Toast.makeText(getActivity(), "Data is saved", Toast.LENGTH_LONG)
					.show();
			android.app.FragmentManager fragmentManager = getFragmentManager();
			android.app.FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			fragmentTransaction
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.replace(R.id.mainfragmentlayout,
					new MySearch_SearchOption_OnSubmit(getActivity(),
							description, suburb, productImagesarray, startdate,
							startime, finishtime, productID, garageSaleTitle,
							oneOrTwoDaySale, unitStreeNo, streeName, city,
							state, postCodearray, earlyBirdMessage,
							badWeatherMessage, goodsTypearray, currentUser,
							longitude, latitude));
			fragmentTransaction.commit();

		}

		@Override
		protected void onProgressUpdate(String... values) {

			super.onProgressUpdate(values);
		}

	}

}
